package com.vichat.common.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by dongql on 2015/6/5.
 */
public class UDPHelper {
    private static transient Logger logger = LoggerFactory.getLogger(UDPHelper.class);
    public static final String TAG = "##UDPHelper";

    //private WifiManager.MulticastLock lock = null;
    private String message;
    private boolean flag = false;

    private int count = 1;


    public UDPHelper(String message, int count) {


        this.message = message;
        this.count = count;
    }

    public String send(String host, int port) throws Exception {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            socket.setSoTimeout(2000);

            //int msgLength = message.length();
            byte[] data = message.getBytes();
            InetAddress address = InetAddress.getByName(host);
            DatagramPacket pack = new DatagramPacket(data, data.length, address, port);

            byte[] buf = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
            flag = false;
            while(!flag && count-- >= 0){
                try {
                    socket.send(pack);
                    socket.receive(receivePacket);
                    flag = true;
                    break;
                } catch (Exception ee) {
                    logger.error(TAG, "no data received: ",ee);
                }
            }

            if(flag){
                String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
                logger.error(TAG, "data:" + received);
                return received;
            } else {
                throw new Exception("数据上传失败");
            }

        } catch (Exception e) {
            logger.error(TAG, "error:" , e);
            return "error";
        } finally {
            try {
                if(socket!=null){
                    socket.close();
                }
            }catch(Exception e){

            }
        }
    }

}
